import { Text, useMessage } from 'alemonjs'
import { validate, selects } from '@src/apps/index'
import { ioredis, user, battle, skill_list } from '@src/db'
import { qidToUid, getUserStatus } from '@src/apps/tools'
import { getCampActionStatus } from '@src/apps/battle/battle'

export const regular = /^(!|！|\/)?技能\s*(\S+)/

const response = onResponse(selects, async e => {
  const [message] = useMessage(e)
  const userId = await qidToUid(e.UserId ?? e.UserKey)
  const msg = e.MessageText?.trim() || ''

  // 检查用户状态，只有战斗状态才允许操作
  const state = await getUserStatus(userId)
  if (state !== 6) {
    message.send(format(Text('\n你不在战斗，无法操作！')))
    return
  }

  // 匹配技能指令
  const match = /^(!|！|\/)?技能\s*(\S+)/i.exec(msg)
  if (!match) {
    message.send(format(Text('\n无效指令')))
    return
  }
  const skillName = match[2]

  // 获取当前战斗信息
  const battleInfo = await battle.findOneValue({
    where: { uid: userId }
  })

  if (!battleInfo) {
    message.send(format(Text('\n未找到当前战斗信息，请联系管理员！')))
    return
  }
  const battle_id = Number(battleInfo.battle_id)
  const battle_camp = Number(battleInfo.battle_camp)
  const battle_index = Number(battleInfo.battle_index)

  // 默认技能距离1（如需根据技能表调整可在此处查询技能距离）
  let distance = 1

  // 获取技能信息
  const skillInfo = await skill_list.findOneValue({
    where: { name: skillName }
  })
  if (!skillInfo) {
    message.send(format(Text('\n该技能不存在！')))
    return
  }
  // 如果技能有指定距离，则使用该距离
  distance = Number(skillInfo.distance)

  // 获取目标
  const targetKey = `fantasy:battle:${battle_id}:${battle_camp}:${battle_index}:target`
  const targetPosition = await ioredis.get(targetKey)

  // 判断目标是否锁定
  if (!targetPosition) {
    message.send(format(Text('\n目标未锁定！')))
    return
  }

  // 判断自己和目标的前后排
  // 约定：1/2/3为前排，4/5/6为后排
  const getRow = (idx: number) => (Number(idx) <= 3 ? 'front' : 'back')

  // 获取敌方阵营
  const enemy_camp = battle_camp === 1 ? 2 : 1

  // 查询目标的battle_index
  const enemyMembers = await battle.findAllValues({
    where: { battle_id, battle_camp: enemy_camp }
  })
  const targetMember = enemyMembers.find(
    m => String(m.position) === String(targetPosition)
  )
  if (!targetMember) {
    message.send(format(Text(`\n目标[${targetPosition}]为空！`)))
    return
  }
  const target_index = Number(targetMember.battle_index)

  // 判断距离
  const myRow = getRow(battle_index)
  const targetRow = getRow(target_index)
  // 双方实际距离
  const actualDistance = Math.abs(
    Number(myRow === 'front' ? 1 : 2) +
      Number(targetRow === 'front' ? 1 : 2) -
      1
  )
  const canAttack = actualDistance <= distance

  if (!canAttack) {
    message.send(
      format(
        Text(
          `\n目标[${targetPosition}]过远！\n实际距离 ${actualDistance}\n技能距离 ${distance}`
        )
      )
    )
    return
  }

  // 存入内存数据库"技能:xxx"
  await ioredis.set(
    `fantasy:battle:${battle_id}:${battle_camp}:${battle_index}:action`,
    `技能:${skillName}`
  )

  const { reply } = await getCampActionStatus(battle_id, battle_camp, e)

  message.send(format(Text(reply)))

  return
})

export default onResponse(selects, [validate, response.current])
